<template>
  <ContentWrap :style="`height: ${contentHeight}px`">
    <div class="btn routeHeader">
      <el-button
        type="primary"
        @click="handleForm"
        :loading="btnLoading"
        v-if="
          formType === 'create' ||
          (formType === 'update' && [10, 20, 30].includes(formData.dictGetMaterialsFormStatus))
        "
        v-hasPermi="['produce:get-materials-form:save']"
      >
        保存
      </el-button>
      <el-button
        type="primary"
        @click="printMaterial"
        :loading="btnLoading"
        v-if="formType === 'update' && [10, 20, 30].includes(formData.dictGetMaterialsFormStatus)"
        v-hasPermi="['produce:get-materials-form:print']"
      >
        打印领料单
      </el-button>
      <el-button plain @click="goBack"> 返回 </el-button>
    </div>
    <el-scrollbar :max-height="`${contentHeight - 73}px`">
      <el-form
        ref="formRef"
        :inline="true"
        :model="formData"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-form-item label="产品编号" prop="productNumber">
          <el-input
            v-model="formData.productNumber"
            @change="getProduct"
            :disabled="['view', 'update'].includes(formType)"
            placeholder="请输入产品编号"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="formData.productName"
            :disabled="['view', 'update'].includes(formType)"
            placeholder="请输入产品名称"
          />
        </el-form-item>
        <el-form-item label="产品图号" prop="productDrawingNumber">
          <el-input
            v-model="formData.productDrawingNumber"
            :disabled="['view', 'update'].includes(formType)"
            placeholder="请输入产品图号"
          />
        </el-form-item>
        <el-form-item label="产品规格" prop="productStandard">
          <el-input
            v-model="formData.productStandard"
            :disabled="['view', 'update'].includes(formType)"
            placeholder="请输入产品规格"
          />
        </el-form-item>
        <el-form-item label="领料单号" prop="getMaterialsFormNumber">
          <el-input
            v-model="formData.getMaterialsFormNumber"
            disabled
            placeholder="请输入领料单号"
          />
        </el-form-item>
      </el-form>
      <div class="btn">
        <el-button
          type="primary"
          @click="chooseMaterial"
          v-if="
            formType === 'create' ||
            (formType === 'update' && [10, 20, 30].includes(formData.dictGetMaterialsFormStatus))
          "
          v-hasPermi="['produce:get-materials-form:create']"
        >
          选择物料
        </el-button>
      </div>
      <el-table border :data="formData.details" v-loading="formLoading">
        <el-table-column
          label="序号"
          header-align="center"
          align="center"
          fixed="left"
          type="index"
        />
        <el-table-column
          label="材料类别"
          header-align="left"
          align="left"
          prop="materialCategory"
          min-width="200px"
        />
        <el-table-column
          label="物料编号"
          header-align="left"
          align="left"
          prop="materialNumber"
          min-width="200px"
        />
        <el-table-column
          label="物料名称"
          header-align="left"
          align="left"
          prop="materialName"
          min-width="200px"
        />
        <el-table-column
          label="材质"
          header-align="left"
          align="left"
          prop="material"
          min-width="200px"
        />
        <el-table-column
          label="规格"
          header-align="left"
          align="left"
          prop="specification"
          min-width="200px"
        />
        <el-table-column
          label="单位"
          header-align="left"
          align="left"
          prop="dictUnit"
          min-width="200px"
        />
        <el-table-column
          label="下料尺寸（总）"
          header-align="left"
          align="left"
          prop="baitingTotalSize"
          min-width="200px"
        />
        <el-table-column
          label="工艺尺寸（总）"
          header-align="left"
          align="left"
          prop="processTotalSize"
          min-width="200px"
        />
        <el-table-column
          label="下料尺寸总重(kg)"
          header-align="left"
          align="left"
          prop="baitingTotalWeight"
          min-width="200px"
        />
        <el-table-column
          label="工艺尺寸总重(kg)"
          header-align="left"
          align="left"
          prop="processTotalWeight"
          min-width="200px"
        />
        <el-table-column
          label="需求数量"
          header-align="left"
          align="left"
          prop="requireQuantity"
          min-width="200px"
        />
        <el-table-column
          label="已领数量"
          header-align="left"
          align="left"
          prop="haveQuantity"
          min-width="200px"
        />
        <el-table-column
          label="领取数量"
          header-align="left"
          align="left"
          prop="getQuantity"
          min-width="200px"
        >
          <template #default="scope">
            <el-input
              v-nextInput="'getQuantity'"
              name="getQuantity"
              v-model="scope.row.getQuantity"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          v-if="['create', 'update'].includes(formType)"
          header-align="left"
          align="left"
          min-width="80px"
        >
          <template #default="scope">
            <el-button
              link
              type="danger"
              :loading="deleteLoading"
              @click="handleDelete(scope.$index, scope.row.id)"
            >
              移除行
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </ContentWrap>
  <!-- 选择物料 -->
  <MaterialsOrder
    @getMaterialsOrder="getMaterialsOrder"
    :contentHeight="contentHeight"
    ref="materialsOrder"
  />
  <!-- 打印 -->
  <div v-show="false" id="printData">
    <Print :info="formData" :list="formData.details" />
  </div>
</template>
<script setup lang="ts">
  import * as GetMaterialsFormApi from '@/api/produce/workOrderManagement/getMaterialsForm'
  import MaterialsOrder from './MaterialsOrder.vue'
  import Print from './print.vue'
  import { useTagsViewStore } from '@/store/modules/tagsView'

  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗

  const dialogTitle = ref('') // 弹窗的标题
  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const deleteLoading = ref(false)
  const formType = ref('') // 表单的类型：create - 新增；update - 修改
  const formData = ref({
    id: undefined,
    productNumber: undefined,
    productName: undefined,
    getMaterialsFormNumber: undefined,
    productDrawingNumber: undefined,
    productStandard: undefined,
    dictGetMaterialsFormStatus: undefined,
    details: []
  })
  const btnLoading = ref(false)
  const materialsOrder = ref() //物料弹窗
  const formRef = ref()
  const contentHeight = ref(0)

  // 删除
  const handleDelete = async (index: number, id: number) => {
    console.log(index, id)
    if (formType.value === 'create') {
      formData.value.details.splice(index, 1)
    } else {
      deleteLoading.value = true
      if (id) {
        try {
          await GetMaterialsFormApi.deleteGetMaterials(id)
          message.success('删除行成功')
          getData()
        } finally {
          deleteLoading.value = false
        }
      } else {
        formData.value.details.splice(index, 1)
        deleteLoading.value = false
      }
    }
  }

  /** 获取数据 */
  const { query } = useRoute() // 路由的查询
  const getData = async () => {
    dialogTitle.value = t('action.' + (query as any).type)
    formType.value = (query as any).type
    if ((query as any).id) {
      formLoading.value = true
      try {
        formData.value = await GetMaterialsFormApi.getGetMaterialsForm((query as any).id)
      } finally {
        formLoading.value = false
      }
    }
  }

  // 获取产品信息
  const getProduct = async (number: string) => {
    const res = await GetMaterialsFormApi.getProductInfo({ productNumber: number })
    formData.value.productName = res.productName
    formData.value.productDrawingNumber = res.productDrawingNumber
    formData.value.productStandard = res.productStandard
  }

  // 选择物料
  const chooseMaterial = () => {
    if (formData.value.productNumber) {
      if (formData.value.details.length) {
        materialsOrder.value.open(formData.value.productNumber, formData.value.details)
      } else {
        materialsOrder.value.open(formData.value.productNumber)
      }
    }else {
      message.notifyError('请输入产品编号')
    }
  }

  /**返回 */
  const tagsViewStore = useTagsViewStore()
  const route = useRouter() // 路由
  const goBack = async () => {
    //获取当前路由并删除tagView
    tagsViewStore.delView(route.currentRoute.value)
    //跳转列表页
    route.push({
      path: '/produce/produce/workOrderManagement/getMaterialsForm'
    })
  }

  // 保存
  const handleForm = async () => {
    const arr = formData.value.details
    for (let i = 0; i < arr.length; i++) {
      if (!arr[i]['getQuantity'] || parseFloat(arr[i]['getQuantity']) === 0) {
        message.notifyError('领取数量不能为空或零')
        return
      }
      if (
        parseFloat(arr[i]['getQuantity']) + parseFloat(arr[i]['haveQuantity']) >
        parseFloat(arr[i]['requireQuantity'])
      ) {
        message.notifyError('领取数量和已领数量之和不能大于需求数量')
        return
      }
    }
    btnLoading.value = true
    try {
      if (formType.value === 'create') {
        const data = formData.value as unknown as GetMaterialsFormApi.GetMaterialsFormVO
        await GetMaterialsFormApi.createGetMaterialsForm(data)
        message.success('保存成功')
      } else {
        const data = formData.value as unknown as GetMaterialsFormApi.GetMaterialsFormVO
        await GetMaterialsFormApi.updateGetMaterialsForm(data)
        message.success('保存成功')
      }
      goBack()
    } finally {
      btnLoading.value = false
    }
  }

  // 打印领料单
  const printMaterial = () => {
    // 新建窗口
    let winName, head, bdHtml
    winName = window.open('', '_blank', '') // 新窗口
    head = '<link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />'
    const tabStyle = `
    <style>
      .disFlex {
        display: flex;
      }
      .justifySpaceBetween {
        justify-content: space-between;
      }
      .title {
        font-size: 22px;
        text-align: center;
        margin-bottom: 15px;
      }
      /deep/ .el-table thead th {
        border-right: 1px solid #edeef5 !important;
      }
      .tab {
        border: 1px solid #ebeef5;
      }
      .tabHead, .tabBody {
        text-align: center;
      }
      .tabHead {
        line-height: 30px;
      }
      .borderTop {
        border-top: 1px solid #ebeef5;
      }
      .cell {
        width: 120px;
      }
      .cell:not(:first-child) {
        border-left: 1px solid #efeef5;
      }
    </style>
    `
    head += tabStyle
    bdHtml = window.document.querySelector('#printData').innerHTML
    winName.document.head.innerHTML = head
    winName.document.body.innerHTML = bdHtml
    winName.focus() //聚焦保证页面正常
    setTimeout(() => {
      winName.print()
    }, 500)
  }

  // 获取物料
  const getMaterialsOrder = (val) => {
    formData.value.details = val
  }

  onMounted(() => {
    contentHeight.value = document.body.clientHeight - 125
    getData()
  })
</script>
<style lang="scss" scoped>
  .btn {
    margin-bottom: 10px;
  }
</style>
